/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.client.buz;

import ChatSoft.model.ChatMessage;
import ChatSoft.model.ConnectChatVoiceMessage;
import ChatSoft.model.FileRequestMessage;
import ChatSoft.model.FileResponseMessage;
import ChatSoft.model.MessageBase;
import ChatSoft.model.ServerInfo;
import ChatSoft.model.UserData;
import ChatSoft.model.User;
import ChatSoft.model.VoiceRequestMessage;
import ChatSoft.model.VoiceResponseMessage;
import ChatSoft.model.buz.SendObject;
import chatsoft.client.ui.ChatFrame;
import chatsoft.client.ui.LoginFrame;
import chatsoft.client.ui.MainFrame;
import chatsoft.client.voicechat.Tx;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author KID
 */
public class ClientController extends Thread {

    ObjectInputStream inStream;
    ObjectOutputStream outStream;
    ChatFrame chatFrame;
    MainFrame mainFrame;
    User user;
    LoginFrame loginFrame;
    SourceDataLine sourceDataLine;
    byte tempBuffer[] = new byte[10000];
    Socket sock;

    public ClientController(ObjectInputStream inStream, ObjectOutputStream outStream, LoginFrame loginFrame) {
        this.inStream = inStream;
        this.outStream = outStream;
        this.loginFrame = loginFrame;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Object receiveObject = inStream.readObject();
                if (receiveObject == null) {
                    continue;
                }

                if (receiveObject instanceof UserData) {
                    UserData dataTranfer = (UserData) receiveObject;
                    //ket qua login
                    if (dataTranfer != null && dataTranfer.getCommandName().equals("loginResult")) {
                        user = dataTranfer.getUser();
                        if (user == null) {
                            JOptionPane.showMessageDialog(null, "UserName or Password wrong!");
                        } else {
                            mainFrame = new MainFrame(outStream, user);
                            mainFrame.setVisible(true);
                            loginFrame.dispose();
                        }
                        //ket qua dang ky
                    } else if (dataTranfer != null && dataTranfer.getCommandName().equals("registerResult")) {
                        if (!dataTranfer.getResult()) {
                            JOptionPane.showMessageDialog(null, "UserName already exist!");
                        } else {
                            JOptionPane.showMessageDialog(null, "Create Account success!");
                        }
                        //ket qua cap nhat
                    } else if (dataTranfer != null && dataTranfer.getCommandName().equals("updateAccountResult")) {
                        if (!dataTranfer.getResult()) {
                            JOptionPane.showMessageDialog(null, "add friend fails!");
                        } else {
                            mainFrame.user = dataTranfer.getUser();
                            JOptionPane.showMessageDialog(null, "add friend success!");
                            mainFrame.initFriendList();
                        }
                        //ket qua yeu cau chat
                    } else if (dataTranfer != null && dataTranfer.getCommandName().equals("requestChatResult")) {
                        if (dataTranfer.getChatRequestResult()) {
                            chatFrame = new ChatFrame(outStream, dataTranfer.getRequestChatWith(), dataTranfer.getUser());
                            chatFrame.setVisible(true);
                        } else {
                            JOptionPane.showMessageDialog(null, "Your Friend are not Online!");
                        }
                    }
                } else if (receiveObject instanceof ChatMessage) {
                    ChatMessage chatMessage = (ChatMessage) receiveObject;
                    if (chatFrame == null) {
                        chatFrame = new ChatFrame(outStream, chatMessage.getReceiveFrom(), user);
                        chatFrame.setVisible(true);
                    }
                    chatFrame.addMessage(chatMessage.getMessage(), chatMessage.getReceiveFrom());
                } else if (receiveObject instanceof FileRequestMessage) {
                    FileRequestMessage request = (FileRequestMessage) receiveObject;
                    boolean OK = chatFrame.showVerifyFileBox();
                    
                    if (OK) {
                        
                        File file;
                        
                        final JFileChooser fc = new JFileChooser();
                        fc.showSaveDialog(null);
                        file = fc.getSelectedFile();

                        if (file.exists()) {
                            file.delete();
                        }
                        
                        sock = new Socket(ServerInfo.ip, 7777);

                        ObjectOutputStream o = new ObjectOutputStream(sock.getOutputStream());
                        chatFrame.sendConnectFile(o);

                        ReveiveFileBusiness bus = new ReveiveFileBusiness(sock, file);
                        bus.start();    
                    }
                    
                    FileResponseMessage response = new FileResponseMessage();
                    response.setSendTo(request.getReceiveFrom());
                    response.setReceiveFrom(request.getSendTo());

                    if (OK) {
                        response.setResult("OK");
                    } else {
                        response.setResult("Cancel");
                    }

                    new ChatBussiness(outStream).sendFileResponse(response);

                    
                } else if (receiveObject instanceof FileResponseMessage) {
                    FileResponseMessage response = (FileResponseMessage) receiveObject;
                    if (response.getResult().equals("OK")) {
                        System.out.println("vdsgbsadghs");
                        sock = new Socket(ServerInfo.ip, 7777);

                        ObjectOutputStream o = new ObjectOutputStream(sock.getOutputStream());                    
                        chatFrame.sendFile(sock, o);
                        
                    }
                } else if (receiveObject instanceof VoiceRequestMessage) {
                    VoiceRequestMessage request = (VoiceRequestMessage) receiveObject;
                    boolean OK = chatFrame.showVerifyBox();
                    
                    if (OK) {
                        sock = new Socket(ServerInfo.ip, 5555);

                        ObjectOutputStream o = new ObjectOutputStream(sock.getOutputStream());
                        chatFrame.sendConnectVoice(o);

                        new ReceiveVoiceBusiness(sock).captureAudio();

                        try {
                            new SendVoiceBusiness(sock);
                        } catch (LineUnavailableException ex) {
                            Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                    
                    VoiceResponseMessage response = new VoiceResponseMessage();
                    response.setSendTo(request.getReceiveFrom());
                    response.setReceiveFrom(request.getSendTo());
                    if (OK) {
                        response.setResult("OK");
                    } else {
                        response.setResult("Cancel");
                    }

                    new ChatBussiness(outStream).sendVoiceResponse(response);

                    
                } else if (receiveObject instanceof VoiceResponseMessage) {
                    VoiceResponseMessage response = (VoiceResponseMessage) receiveObject;
                    if (response.getResult().equals("OK")) {
                        System.out.println("vdsgbsadghs");
                        sock = new Socket(ServerInfo.ip, 5555);

                        ObjectOutputStream o = new ObjectOutputStream(sock.getOutputStream());
                        chatFrame.sendConnectVoice(o);

                        new ReceiveVoiceBusiness(sock).captureAudio();

                        try {
                            new SendVoiceBusiness(sock);
                        } catch (LineUnavailableException ex) {
                            Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }
}
